﻿using Bricks.Business.Service;
using Bricks.Business.Service.Impl;
using Bricks.Site.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Bricks.Component.Utils.Extensions;
using Bricks.Business.Service.CommonSupport;
using Bricks.Component.Utils;
using Bricks.Business.Models.SafetyManagement;

namespace Bricks.Site.Web.Controllers
{
    /// <summary>
    /// 安全管理-安全整改
    /// </summary>
    [Export]
    public class SavetyCorrectiveController : BaseController
    {
        [Import]
        public ISavetyCorrectiveService SavetyCorrectiveService { get; set; }

        [Import]
        public IOrgInfoService OrgInfoService { get; set; }

        [Import]
        public ICircularService CircularService { get; set; }

        [Import]
        public IDocumentService DocumentService { get; set; }

        public ActionResult Index()
        {
            ViewBag.ToolBarInfo = base.GetToolBarInfo();
            return View();
        }

        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDataList(int rows = 20, int page = 1)
        {
            var queryData = SavetyCorrectiveService.SavetyCorrectives.OrderByDescending(m => m.FormTime).Skip(rows * (page - 1)).Take(rows).ToList();
            var list = from m in queryData
                       select new SavetyCorrectiveView
                       {
                           ID = m.ID,
                           CorrectiveTitle = m.CorrectiveTitle,
                           CircularID = m.CircularID,
                           FormTime = m.FormTime,
                           FormOrgID = m.FormOrgID,
                           FormOrg = OrgInfoService.GetOrgNameByID(m.FormOrgID),
                           FormUserID = m.FormUserID,
                           FormUser = UserInfoService.GetUserNameByID(m.FormUserID),
                           Content = m.Content,
                           FinishCondition = m.FinishCondition,
                           CorrectiveDemand = m.CircularID.HasValue ? CircularService.GetCircularNameByID(m.CircularID.Value) : string.Empty,  //通过通报ID获取通报内容（作为整改要求）
                           IsDeleted = m.IsDeleted,
                           AddDate = m.AddDate,
                           LoginUserID = SystemData.Instance.CurrentUser.ID
                       };
            var result = new { total = SavetyCorrectiveService.SavetyCorrectives.Count(), rows = list };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Edit(string id)
        {
            SavetyCorrectiveView model = new SavetyCorrectiveView();
            //如果是编辑
            if (!String.IsNullOrEmpty(id))
            {
                Guid guidID = id.ToGuid();
                var record = SavetyCorrectiveService.SavetyCorrectives.FirstOrDefault(m => m.ID == guidID);
                if (record != null)
                {
                    model = record.CopyTo<SavetyCorrectiveView>();
                    model.FormUser = UserInfoService.GetUserInfoByID(model.FormUserID).UserName;
                    //model.PublishOrg = OrgInfoService.GetOrgNameByID(model.PublishOrgID);

                    //整改要求
                    if (model.CircularID.HasValue && !model.CircularID.Equals(Guid.Empty))
                    {
                        model.CorrectiveDemand = CircularService.GetCircularNameByID(model.CircularID.Value);
                    }
                }
            }
            //新增
            else
            {
                model.FormTime = DateTime.Now;
                model.FormUserID = SystemData.Instance.CurrentUser.ID;
                model.FormUser = SystemData.Instance.CurrentUser.UserName;
            }
            return View(model);
        }

        /// <summary>
        /// 新增或编辑（响应）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]  //添加这个是为了防止错误：从客户端中检测到有潜在危险的 Request.Form 值
        public ActionResult EditPost(SavetyCorrectiveView model)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            var record = SavetyCorrectiveService.SavetyCorrectives.FirstOrDefault(m => m.ID == model.ID);

            //新增
            if (record == null)
            {
                record = model.CopyTo<SavetyCorrective>();
                result = SavetyCorrectiveService.Add(record);
                //if (result.ResultType == OperationResultType.Success)
                //    return View(result.AppendData);
            }
            //修改
            else
            {
                record = model.CopyTo<SavetyCorrective>();
                result = SavetyCorrectiveService.Modify(record);
                //if (result.ResultType == OperationResultType.Success)
                //    return View(result.AppendData);
            }
            //return View();
            return Json(result, "text/html");
        }

        public ActionResult Preview(string id)
        {
            SavetyCorrectiveView model = new SavetyCorrectiveView();
            //如果是编辑
            if (!String.IsNullOrEmpty(id))
            {
                Guid guidID = id.ToGuid();
                var record = SavetyCorrectiveService.SavetyCorrectives.FirstOrDefault(m => m.ID == guidID);
                if (record != null)
                {
                    model = record.CopyTo<SavetyCorrectiveView>();
                    model.FormUser = UserInfoService.GetUserInfoByID(model.FormUserID).UserName;
                    model.FormOrg = OrgInfoService.GetOrgNameByID(model.FormOrgID);

                    //整改要求
                    if (model.CircularID.HasValue && !model.CircularID.Equals(Guid.Empty))
                    {
                        model.CorrectiveDemand = CircularService.GetCircularNameByID(model.CircularID.Value);
                    }
                }
            }
            return View(model);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(string id)
        {
            OperationResult exeResult = new OperationResult(OperationResultType.Success);
            Guid guidID = id.ToGuid();
            var record = SavetyCorrectiveService.SavetyCorrectives.FirstOrDefault(m => m.ID == guidID);
            if (record != null)
            {
                //如果当前登录用户不是发布人，则不允许删除
                if (!SystemData.Instance.CurrentUser.ID.Equals(record.FormUserID))
                {
                    exeResult = new OperationResult(OperationResultType.Warning, "非发布人不允许删除记录");
                }
                else
                {
                    exeResult = SavetyCorrectiveService.Delete(guidID);
                    if (exeResult.ResultType == OperationResultType.Success)
                    {
                        var docDeleteResult = DocumentService.DeleteByInstanceID(guidID);
                        if (docDeleteResult == true)
                        {
                            exeResult.Message += "，已删除关联附件记录";
                        }
                    }
                }
            }
            return Json(exeResult);
        }

        /// <summary>
        /// 预览详细通报
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Detail(string id)
        {
            return Preview(id);
        }
    }
}
